package com.ashley.apptools.provider;


import java.util.HashMap;

import com.ashley.apptools.provider.ToolsData.Category;
import com.ashley.apptools.provider.ToolsData.ItemNumber;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

public class ToolsContentProvider extends ContentProvider {
	private DatabaseHelper mOpenHelper;	
	private static HashMap<String, String> sCategoryProjectionMap;
	private static HashMap<String, String> sItemProjectionMap;
	private static final int CATEGORY = 1;
	private static final int CATEGORY_ID = 2;
	private static final int ITEM =3;
	private static final int ITEM_ID = 4;
	
    private static final UriMatcher sUriMatcher;
    static {
    	sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    	sUriMatcher.addURI(ToolsData.AUTHORITY, "category", CATEGORY);
    	sUriMatcher.addURI(ToolsData.AUTHORITY, "category/#", CATEGORY_ID);
    	sUriMatcher.addURI(ToolsData.AUTHORITY, "itemnumber", ITEM);
    	sUriMatcher.addURI(ToolsData.AUTHORITY, "itemnumber/#", ITEM_ID);
    	
    	sCategoryProjectionMap = new HashMap<String, String>();
    	sCategoryProjectionMap.put(Category._ID, Category._ID);
    	sCategoryProjectionMap.put(Category.COLUMN_NAME_TITLE,Category.COLUMN_NAME_TITLE);
    	sCategoryProjectionMap.put(Category.COLUME_LANDING,Category.COLUME_LANDING);
    	sCategoryProjectionMap.put(Category.COLUME_WAREHOVSE,Category.COLUME_WAREHOVSE);
    	sCategoryProjectionMap.put(Category.COLUME_SALE,Category.COLUME_SALE);
    	
    	
    	sItemProjectionMap = new HashMap<String, String>();
    	sItemProjectionMap.put(ItemNumber._ID, ItemNumber._ID);
    	sItemProjectionMap.put(ItemNumber.COLUME_CATEGORY, ItemNumber.COLUME_CATEGORY);
    	sItemProjectionMap.put(ItemNumber.COLUME_ITEM_NO, ItemNumber.COLUME_ITEM_NO);
    	sItemProjectionMap.put(ItemNumber.COLUME_FREIGHT, ItemNumber.COLUME_FREIGHT);
    	sItemProjectionMap.put(ItemNumber.COLUME_PRICE, ItemNumber.COLUME_PRICE);
    	sItemProjectionMap.put(ItemNumber.COLUME_TAX, ItemNumber.COLUME_TAX);
    	sItemProjectionMap.put(ItemNumber.COLUME_LANDING, ItemNumber.COLUME_LANDING);
    	sItemProjectionMap.put(ItemNumber.COLUME_WAREHOVSE, ItemNumber.COLUME_WAREHOVSE);
    	sItemProjectionMap.put(ItemNumber.COLUME_SALE, ItemNumber.COLUME_SALE);
    	sItemProjectionMap.put(ItemNumber.CLUME_RETAIL, ItemNumber.CLUME_RETAIL);
    	
    }
	public ToolsContentProvider() {
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// Implement this to handle requests to delete one or more rows.
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = 0;
        String finalWhere = null;
        String table = null;
        String uid = null;
        switch (sUriMatcher.match(uri)) {
		case CATEGORY:
			table = Category.TABLE_NAME;
			finalWhere = selection;
			break;
		case CATEGORY_ID:
			table = Category.TABLE_NAME;
			uid = uri.getPathSegments().get(1);
			finalWhere = Category._ID + " = " + uid;
			if(selection !=null)
			{
				finalWhere = finalWhere + " AND " +selection;
			}
			break;
		case ITEM:
			table = ItemNumber.TABLE_NAME;
			finalWhere = selection;
			
			break;
		case ITEM_ID:
			table = ItemNumber.TABLE_NAME;
			uid = uri.getPathSegments().get(1);
			finalWhere = ItemNumber._ID + " = " +uid;
			if(selection !=null)
			{
				finalWhere = finalWhere + " AND " + selection;
			}
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
        if(table !=null)
        {
        	count = db.delete(table, finalWhere, selectionArgs);
        	getContext().getContentResolver().notifyChange(uri, null);
        	return count;
        }
        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public String getType(Uri uri) {
		// TODO: Implement this to handle requests for the MIME type of the data
		// at the given URI.
		switch (sUriMatcher.match(uri)) {
		case CATEGORY:
			return Category.CONTENT_TYPE;
		case CATEGORY_ID:
			
			return Category.CONTENT_ITEM_TYPE;
		case ITEM:
			return ItemNumber.CONTENT_TYPE;
		case ITEM_ID:
			return ItemNumber.CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO: Implement this to handle requests to insert a new row.
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		
		long rowId = 0;
		Uri contentUri = null;
		Long now = Long.valueOf(System.currentTimeMillis());
		values.put("creationtime", now);
		switch (sUriMatcher.match(uri)) {
		case ITEM:
			contentUri = ItemNumber.CONTENT_ID_URI_BASE;
			long newId= check(uri,values.get(ItemNumber.COLUME_CATEGORY),values.get(ItemNumber.COLUME_ITEM_NO));
			if(newId >0)			
			{
				Uri newUri = ContentUris.withAppendedId(contentUri, newId);
				rowId = update(newUri, values, null, null);
				
				newUri = ContentUris.withAppendedId(contentUri, rowId);
				getContext().getContentResolver().notifyChange(newUri, null);
				return newUri;
			}else
			{
				rowId = db.insert(ItemNumber.TABLE_NAME, null, values);
				
			}
			
			break;
		case CATEGORY:
			rowId = db.insert(Category.TABLE_NAME, null, values);
			contentUri = Category.CONTENT_ID_URI_BASE;
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		if(rowId>0)
		{
			Uri newUri = ContentUris.withAppendedId(contentUri, rowId);
			getContext().getContentResolver().notifyChange(newUri, null);
			return newUri;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		// TODO: Implement this to initialize your content provider on startup.
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}
	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO: Implement this to handle query requests from clients.
		SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		switch (sUriMatcher.match(uri)) {
		case CATEGORY:
			builder.setTables(Category.TABLE_NAME);
			builder.setProjectionMap(sCategoryProjectionMap);
			break;
		case CATEGORY_ID:
			builder.setTables(Category.TABLE_NAME);
			builder.setProjectionMap(sCategoryProjectionMap);
			builder.appendWhere(Category._ID +" = " + uri.getPathSegments().get(1));
			break;
		case ITEM:
			builder.setTables(ItemNumber.TABLE_NAME);
			builder.setProjectionMap(sItemProjectionMap);
			break;
		case ITEM_ID:
			builder.setTables(ItemNumber.TABLE_NAME);
			builder.setProjectionMap(sItemProjectionMap);
			builder.appendWhere(ItemNumber._ID +" = " + uri.getPathSegments().get(1));
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		String orderBy;
		if(TextUtils.isEmpty(sortOrder))
		{
			orderBy = ToolsData.DEFAULT_SORT_ORDER;
		}else
		{
			orderBy = sortOrder;
		}
		SQLiteDatabase database = mOpenHelper.getReadableDatabase();
		Cursor cursor = builder.query(database, projection, selection, selectionArgs, null, null, orderBy);
		cursor.setNotificationUri(getContext().getContentResolver(), uri);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO: Implement this to handle requests to update one or more rows.
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count = 0;
        String finalWhere = null;
        String table = null;
        String uid = null;
		switch (sUriMatcher.match(uri)) {
		case CATEGORY:
			table = Category.TABLE_NAME;
			finalWhere = selection;
			break;
		case CATEGORY_ID:
			table = Category.TABLE_NAME;
			uid = uri.getPathSegments().get(1);
			finalWhere = Category._ID +" = " +uid;
			
			if(selection !=null)
			{
				finalWhere = finalWhere+ " AND " + selection;
			}
			
			break;
		case ITEM:
			table = ItemNumber.TABLE_NAME;
			finalWhere = selection;
			break;
		case ITEM_ID:
			table = ItemNumber.TABLE_NAME;
			uid = uri.getPathSegments().get(1);
			finalWhere = ItemNumber._ID + " = " + uid;
			if(selection != null)
			{
				finalWhere = finalWhere + " AND" + selection;
			}
			break;
		default:
			break;
		}
		if(table !=null)
		{
			count = db.update(table, values, finalWhere,selectionArgs);
			getContext().getContentResolver().notifyChange(uri, null);
			return count;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}
	private long check(Uri uri,Object category,Object itemNo)
	{
		SQLiteDatabase database = mOpenHelper.getReadableDatabase();
		Cursor cursor = database.rawQuery(" SELECT _id, category, item FROM itemnumber WHERE (category = "+category+" AND item = '"+itemNo.toString()+"') ORDER BY _id DESC",null);
		for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext())
		{
			int idColumn = cursor.getColumnIndex(ItemNumber._ID);
			return cursor.getLong(idColumn);
		}
				
		return -1;
	}
}
